import redis
import time
import logging
from git import Repo
import subprocess

log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(level=logging.INFO, format=log_format, datefmt=date_format)

logging.info("开始监听代码变化")

repo = Repo(r'/home/chencan/stock/')

branch_name = 'master'


def kill_python_processes():
    try:
        # 构建pkill命令
        cmd = 'killall python'
        # 执行命令
        subprocess.run(['killall', 'python'])
        print("所有 python 进程已被终止。")
    except subprocess.CalledProcessError as e:
        print(f"错误：{e}")


def main():
    r = redis.Redis(host='ccu.local', port=6379, db=0, password="DRC@1234bank")
    pubsub = r.pubsub()

    # 订阅频道
    pubsub.psubscribe('stock_info_code')

    for i in pubsub.listen():
        message = pubsub.get_message()
        logging.info(f"收到消息: {i}")
        if i['type'] == 'pmessage':
            logging.info("开始更新代码")
            repo.git.checkout(branch_name)
            repo.git.fetch('--all')
            repo.git.reset('--hard', f'origin/{branch_name}')
            repo.git.pull('origin', branch_name, '--force')
            repo.git.clean('-fd')

            logging.info("代码更新完成")
            kill_python_processes()
            time.sleep(1)
            subprocess.run(['sh', "/home/chencan/stock/start.sh"])
            logging.info("服务重启完成")
        else:
            logging.info("未收到消息")

if __name__ == "__main__":
    main()

